﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.Common;
using System.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace MaxLeaf.DAL.K2W
{
    public class OeSalesOrderDAL
    {
        internal int Add(DB.DBAccess dbOrgK3Con, DB.DBAccess dbDestWebReadCon, DB.DBAccess dbDestWebWriteCon, string strKeyValue, W2K.OeSalesOrderDAL.FromType mFromType)
        {
            return 0;
        }

        internal int Update(DB.DBAccess dbOrgK3Con, DB.DBAccess dbDestWebReadCon, DB.DBAccess dbDestWebWriteCon, string strKeyValue, W2K.OeSalesOrderDAL.FromType mFromType)
        {
            string strorder_id = GetOrder_ID(dbOrgK3Con, dbDestWebReadCon, strKeyValue, mFromType);
            if (strorder_id.Length == 0) return 0;

            if (mFromType == W2K.OeSalesOrderDAL.FromType.SEOutStockChecked)
            {
                UpdateShipStatus(dbDestWebReadCon, dbDestWebWriteCon, strorder_id, W2K.OeSalesOrderDAL.ShipStatus.SEOutStockChecked);
            }
            else if (mFromType == W2K.OeSalesOrderDAL.FromType.BlueICStockBillChecked)
            {
                UpdateShipStatus(dbDestWebReadCon, dbDestWebWriteCon, strorder_id, W2K.OeSalesOrderDAL.ShipStatus.ICStockBillChecked);
                SetSmSMessage(dbOrgK3Con, strKeyValue);
            }
            else if (mFromType == W2K.OeSalesOrderDAL.FromType.RedICStockBillChecked
                || mFromType == W2K.OeSalesOrderDAL.FromType.RedOtherICStockBillChecked
                )
            {
                UpdateShipStatus(dbDestWebReadCon, dbDestWebWriteCon, strorder_id, W2K.OeSalesOrderDAL.ShipStatus.RedChecked);
                if (mFromType == W2K.OeSalesOrderDAL.FromType.RedOtherICStockBillChecked)
                {
                    UpdatePayStatus(dbDestWebReadCon, dbDestWebWriteCon, strorder_id, W2K.OeSalesOrderDAL.PayStatus.ICSaleChecked);
                }
            }
            else if (mFromType == W2K.OeSalesOrderDAL.FromType.ICSaleChecked || mFromType == W2K.OeSalesOrderDAL.FromType.RedICSaleChecked)
            {
                UpdatePayStatus(dbDestWebReadCon, dbDestWebWriteCon, strorder_id, W2K.OeSalesOrderDAL.PayStatus.ICSaleChecked);
            }
            else if (mFromType == W2K.OeSalesOrderDAL.FromType.ICSaleUnChecked)
            {
                UpdatePayStatus(dbDestWebReadCon, dbDestWebWriteCon, strorder_id, W2K.OeSalesOrderDAL.PayStatus.ICSaleUnChecked);
            }

            return CvtFunc.ToInt(strorder_id);
        }

        private void SetSmSMessage(DB.DBAccess dbOrgK3Con, string strKeyValue)
        {           
            string strSQL = "select * from IcStockBill where FInterID='{0}' and FHeadSelfB0167 ='0'";
            strSQL = string.Format(strSQL, strKeyValue);
            DataRow drRow = dbOrgK3Con.GetDataFirstRow(strSQL );
            if (drRow != null)
            {
                ServiceReference1.infoPortTypeClient tsInfo = new ServiceReference1.infoPortTypeClient();
                string strRegCode = "ZXHD-CRM-0111-UCAFFR";                
                string strPhone ="";
                string[] strPhoneAndCell = CvtFunc.ToString(drRow["FHeadSelfB0158"]).Trim().Split(new char[] { ',' }, StringSplitOptions.None);
                if (strPhoneAndCell.Length==1 && strPhoneAndCell[0].Trim().Length > 0)
                {
                    strPhone = strPhoneAndCell[0].Trim() ;
                }
                else
                {
                    strPhone = strPhoneAndCell[1].Trim();
                }
                if (strPhone == "") return;
                string strContent = "尊敬的 " + CvtFunc.ToString ( drRow["FHeadSelfB0155"]) + " ， 您的订单 " + drRow["FHeadSelfB0152"] + " 已经于 " + DateTime.Now.ToShortDateString() + "  " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + " 发货。请留意查收。";
                //String sendSMS(String Regcode,String Pwd,String Phone,String CONTENT,String Extnum,String Level,String Schtime,String Reportflag,String wapUrl,String smstype)
                //call1.invoke(new Object[]{Regcode, Pwd,  		mobile ,java.net.URLEncoder.encode(content,"gbk"),"", "1", "", "1", "", "4"});

               // string strReutrn = tsInfo.sendSMS(strRegCode, "99729246", strPhone, strContent, "", "1", "", "1", "", "4");
                //if (strReutrn == "0")  //发送成功
                //{
                //}
                strSQL = "update IcStockBill set FHeadSelfB0167 ='1' where FInterID='{0}'";
                strSQL = string.Format(strSQL, strKeyValue);  
                dbOrgK3Con.ExecuteSql(strSQL); 
            }
        }

        public void SendSMS()
        {
            //String sendSMS(String Regcode,String Pwd,String Phone,String CONTENT,String Extnum,String Level,String Schtime,String Reportflag,String wapUrl,String smstype)
            //call1.invoke(new Object[]{Regcode, Pwd,  		mobile ,java.net.URLEncoder.encode(content,"gbk"),"", "1", "", "1", "", "4"});

            ServiceReference1.infoPortTypeClient tsInfo = new ServiceReference1.infoPortTypeClient();
            string strReutrn = tsInfo.sendSMS("testcode", "99729246", "123", "sss", "", "1", "", "1", "", "4");
        }
    

        private void UpdatePayStatus(DB.DBAccess dbDestWebReadCon, DB.DBAccess dbDestWebWriteCon, string strorder_id, W2K.OeSalesOrderDAL.PayStatus payStatus)
        {
            
            string strSQL = @"update k3_order_main set pay_status=?pay_status,pay_time=?pay_time where order_id=?order_id 
                    ";
            dbDestWebWriteCon.ExecuteSql(strSQL, new MySqlParameter[] { 
                    new MySqlParameter("?order_id", strorder_id) 
                    ,new MySqlParameter("?pay_status", ((int)payStatus).ToString()) 
                    ,new MySqlParameter("?pay_time", CvtFunc.ToUnitStamp(DateTime.Now)) 
                });


            //Web 2 SCP
            if (payStatus == W2K.OeSalesOrderDAL.PayStatus.ICSaleUnChecked)
            {
                if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["SCP"]))
                {
                    //反核销
                    strSQL = @"insert into SCP_mLog(logtype,keyvalue,logstatus)
                values(?logtype,?keyvalue,?logstatus)";
                    dbDestWebWriteCon.ExecuteSql(strSQL, new MySqlParameter[] { 
                        new MySqlParameter("?logtype", "order_main") 
                        ,new MySqlParameter("?keyvalue",  strorder_id) 
                        ,new MySqlParameter("?logstatus", "2") 
                    });
                }
            }
        }

        private void UpdateShipStatus(DB.DBAccess dbDestWebReadCon, DB.DBAccess dbDestWebWriteCon, string strorder_id, W2K.OeSalesOrderDAL.ShipStatus shipStatus)
        {
            string strSQL = @"update k3_order_main set ship_status=?ship_status,ship_time=?ship_time where order_id=?order_id";
            dbDestWebWriteCon.ExecuteSql(strSQL, new MySqlParameter[] { 
                    new MySqlParameter("?order_id", strorder_id) 
                    ,new MySqlParameter("?ship_status", ((int)shipStatus).ToString()) 
                    ,new MySqlParameter("?ship_time", CvtFunc.ToUnitStamp(DateTime.Now)) 
                });

            //Web 2 SCP
            if (shipStatus== W2K.OeSalesOrderDAL.ShipStatus.ICStockBillChecked )
            {
                if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["SCP"]))
                {
                    //发货
                    strSQL = @"insert into SCP_mLog(logtype,keyvalue,logstatus)
                values(?logtype,?keyvalue,?logstatus)";
                    dbDestWebWriteCon.ExecuteSql(strSQL, new MySqlParameter[] { 
                        new MySqlParameter("?logtype", "order_main") 
                        ,new MySqlParameter("?keyvalue",  strorder_id) 
                        ,new MySqlParameter("?logstatus", "0") 
                    });
                }
            }
        }

        internal void Delete(DB.DBAccess dbOrgK3Con, DB.DBAccess dbDestWebReadCon, DB.DBAccess dbDestWebWriteCon, string strKeyValue, W2K.OeSalesOrderDAL.FromType mFromType)
        {
            string strSQL = string.Empty;
            string strorder_id = GetOrder_ID(dbOrgK3Con, dbDestWebReadCon, strKeyValue, mFromType);
            
            
            try
            {
                
                if (strorder_id.Length == 0) return;

                strSQL = @"delete from k3_order_main where order_id=?order_id
                    ;update order_main set order_status=?order_status where order_id=?order_id";
                dbDestWebWriteCon.ExecuteSql(strSQL, new MySqlParameter[] { 
                    new MySqlParameter("?order_id", strorder_id) 
                    ,new MySqlParameter("?order_status", ((int)W2K.OeSalesOrderDAL.OrderStatus.Deleted).ToString()) 
                });

            }
            catch (Exception ex)
            {
                throw new MaxLeafException("删除销售单，更新网站状态失败." + ex.ToString());
            }
        }

        private string GetOrder_ID(DB.DBAccess dbOrgK3Con, DB.DBAccess dbDestWebReadCon, string strKeyValue, W2K.OeSalesOrderDAL.FromType mFromType)
        {
            LogManager.Debug("mFromType:" + mFromType);
            string strSQL = string.Empty;

            string strOrderInterID=string.Empty;

            string strOrderType = "1";
            if (mFromType == W2K.OeSalesOrderDAL.FromType.SEOrder
                )
            {
                strOrderInterID = strKeyValue;
            }
            else if(mFromType == W2K.OeSalesOrderDAL.FromType.RedICStockBillDeleted
                || mFromType == W2K.OeSalesOrderDAL.FromType.RedICStockBillChecked
                || mFromType == W2K.OeSalesOrderDAL.FromType.RedOtherICStockBillChecked

                )
            {
                strOrderInterID = strKeyValue;
                strOrderType = "0";
            }
            else if (mFromType == W2K.OeSalesOrderDAL.FromType.RedICSaleChecked
           
            )
            {
                strOrderInterID = GetOrderInterID(dbOrgK3Con, mFromType, strKeyValue);
                strOrderType = "0";
            }
            else 
            {
                strOrderInterID = GetOrderInterID(dbOrgK3Con, mFromType, strKeyValue);
            }
            
            
            strSQL = "select db_id from k3_db_main  where dbname=@dbname";
            DataRow drk3_db_main = dbDestWebReadCon.GetDataFirstRow(strSQL, new MySqlParameter[] {
                    new MySqlParameter("@dbname", dbOrgK3Con.ServerDBName) 
                });
            if (drk3_db_main == null) return string.Empty;

            strSQL =string.Format( @"select * from k3_order_main where db_id=?db_id and  FitemID=?FitemID 
                    and order_id in (select order_id from order_main  where {0})"
                ,(strOrderType.Equals("1", StringComparison.InvariantCultureIgnoreCase) ?" order_type=1 ":"order_type<>1")
                );
            DataRow drk3_order_main = dbDestWebReadCon.GetDataFirstRow(strSQL, new MySqlParameter[]{
                    new MySqlParameter("?db_id",drk3_db_main["db_id"])
                    ,new MySqlParameter("?FitemID",strOrderInterID)
                });
            if (drk3_order_main == null) return string.Empty;
            return CvtFunc.ToString( drk3_order_main["order_id"]);
        }

        private string GetOrderInterID(DB.DBAccess dbOrgK3Con, W2K.OeSalesOrderDAL.FromType mFromType, string strFInterID)
        {
            string strTableName = string.Empty;
            string strInterIDFieldName = "FOrderInterID";
            if (mFromType == W2K.OeSalesOrderDAL.FromType.SEOutStockChecked)
            {
                strTableName = "SEOutStockentry";
            }
            else if (mFromType == W2K.OeSalesOrderDAL.FromType.BlueICStockBillChecked 
                || mFromType == W2K.OeSalesOrderDAL.FromType.RedICStockBillChecked
                || mFromType == W2K.OeSalesOrderDAL.FromType.RedOtherICStockBillChecked
                )
            {
                strTableName = "ICStockBillentry";
            }
            else if (mFromType == W2K.OeSalesOrderDAL.FromType.ICSaleChecked )
            {
                strTableName = "ICSaleentry";
            }
            else if (mFromType == W2K.OeSalesOrderDAL.FromType.ICSaleUnChecked)
            {
                strTableName = "ICSaleentry";
            }
            else if (mFromType == W2K.OeSalesOrderDAL.FromType.RedICSaleChecked)
            {
                strTableName = "ICSaleentry";
                strInterIDFieldName = "FSourceInterID";
            }
            string strSql = string.Format("select {1} from {0} where FInterID=@FInterID {2}"
                , strTableName, strInterIDFieldName
                , ((mFromType == W2K.OeSalesOrderDAL.FromType.RedICSaleChecked) ? "" : " and FOrderInterID<>0")
                );
            DataRow drData = dbOrgK3Con.GetDataFirstRow(strSql, new SqlParameter[]{
                    new SqlParameter("@FInterID",strFInterID)
                    
                });
            if (drData == null) return string.Empty;
            return CvtFunc.ToString(drData[strInterIDFieldName]);
        }
    }
}
